use std::collections::HashSet;
use crate::db::dao::im_department_dao::{count_total_department, department_inserts, department_updates, query_departments_by_codes, query_departments_for_db};
use crate::db::db::Db;
use crate::db::pojo::pojo::{ImDepartment};

pub fn save_departments(_user_id: String, departments: &mut Vec<ImDepartment>) {
    let db = Db::open();
    // transaction(db.clone(), move |db: Db| {
    //     save_departments_business(db, departments)
    // });
    save_departments_business(db.clone(), departments);
}

pub fn query_departments() -> Vec<ImDepartment> {
    let db = Db::open();
    query_departments_for_db(db.clone())
}

pub fn total_department() -> usize {
    let db = Db::open();
    count_total_department(db.clone())
}

fn save_departments_business(db: Db, departments: &mut Vec<ImDepartment>) {
    let codes = departments.iter().map(|department| {department.code.clone()}).collect::<Vec<String>>();
    let db_departments = query_departments_by_codes(db.clone(), codes);
    let db_ids = db_departments.iter().map(|department| {&department.code}).collect::<HashSet<&String>>();

    let mut insert_departments= Vec::new();
    let mut update_departments = Vec::new();

    for department in departments {
        let code = &department.code;
        if !db_ids.contains(code) {
            insert_departments.push(department);
        } else {
            update_departments.push(department);
        }
    }

    department_inserts(db.clone(), &mut insert_departments);
    department_updates(db.clone(), &mut update_departments);
}